package com.lyf.controller;


import com.alibaba.druid.util.StringUtils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lyf.pojo.User;
import com.lyf.service.UserService;
import com.lyf.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("login")
    public Map<String, Object> login(User user){
        log.info("用户名：[{}]",user.getName());
        log.info("密码：[{}]",user.getPassword());
        Map<String, Object> map = new HashMap<>();
        try{
            User userDB = userService.login(user);
            //生成jwt令牌
            Map<String, String> payload = new HashMap<>();
            payload.put("id", String.valueOf(userDB.getId()));
            payload.put("name", userDB.getName());

            String token = JWTUtils.getToken(payload);
            map.put("state", true);
            map.put("msg","登入成功");
            map.put("token", token);//响应token
        } catch (Exception e){
            e.printStackTrace();
            map.put("state", false);
            map.put("msg","登入失败");
        }
        return map;
    }

    @PostMapping("test")
    public Map<String, Object> test(HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        //处理自己的业务逻辑
        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtils.verify(token);
        log.info("用户id：[{}]",verify.getClaim("id").asString());
        log.info("用户名：[{}]",verify.getClaim("name").asString());

        map.put("state", true);
        map.put("msg", "请求成功");

        return map;
    }
}
